package study.intconsulting.net.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import study.intconsulting.util.NIOUtil;

public class HongClass {

	private static final String HOST = "localhost";
	private static final int PORT = 9090;
	
	private SocketChannel sc = null;
	private Selector selector = null;
	
	public HongClass() throws Exception{
		initClient();
	}
	
	public void initClient() throws Exception{
		selector = Selector.open();
		sc = SocketChannel.open(new InetSocketAddress(HOST,PORT));
		sc.configureBlocking(false);
		sc.register(selector, SelectionKey.OP_READ);
	}
	
	public String call(String reqXml){
		String xml = null;
		try{
			sc.write(ByteBuffer.wrap(reqXml.getBytes()));
			
			while(true){
				if(selector.select() <= 0){
					continue;
				}
				
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();
				
				while(it.hasNext()){
					SelectionKey key = (SelectionKey)it.next();
					
					if(key.isReadable()){
						xml = read(key);
					}
					it.remove();
				}				
			}
		}catch(Exception e){
			
		}
		return xml;
	}
	
	private String read(SelectionKey key){
		String xml = null;
		SocketChannel sc = (SocketChannel)key.channel();

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		try{
			if(sc.read(buffer) > 0){
				buffer.flip();
				xml = NIOUtil.bufferToString(buffer);

				shutdown(sc);
			}else{
				shutdown(sc);			
			}
		}catch(IOException e){
			shutdown(sc);
		}
		return xml;
	}		
	
	private void shutdown(SocketChannel sc){
		try{
			sc.close();
			selector.close();
		}catch (IOException e){
			e.printStackTrace();
		}
	}		
		
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		String reqXml = "<message><who>who</who></message>";
		HongClass hongClass = new HongClass();
		String resXml = hongClass.call(reqXml);
		System.out.println("result : " + resXml);
	}
}